﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using IPR_StudyMeetingMrgSys.ViewModel;
using IPR_StudyMeetingMrgSys.Models;
using IPR_StudyMeetingMrgSys.Enums;
using IPR_StudyMeetingMrgSys.Extension;
using IPR_StudyMeetingMrgSys.BLL;
using IPR_StudyMeetingMrgSys.Model;
using Newtonsoft.Json;
using log4net;
using System.Reflection;
using System.Data;
using System.Web;
using System.IO;
using IPR_StudyMeetingMrgSys.Common;
using System.Web.Http.Cors;

namespace IPR_StudyMeetingMrgSys.Controllers
{
    public class UserInfoController : ApiController
    {
        ILog log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        // GET: api/UserInfo
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET: api/UserInfo/5
        public string Get(int id)
        {
            Model.UserInfo memp = new Model.UserInfo();
            memp = new BLL.UserInfo().GetModel(id);
            return JsonConvert.SerializeObject(memp);
            //return "value";
        }
        /// <summary>
        /// 获取人员信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("api/UserInfo/GetUserInfoDetail")]
        public IHttpActionResult GetUserInfoDetail(int id)
        {
            ResultMsg resultMsg = new ResultMsg();
            resultMsg.StatusCode = (int)StatusCodeEnum.Success;
            try
            {
                DataTable dt = new BLL.UserInfo().GetEmployeeDetail(id);
                resultMsg.Info = dt.Rows.Count > 0 ? StatusCodeEnum.Success.GetEnumText() : "未获取到相应数据";
                resultMsg.Count = dt.Rows.Count;
                resultMsg.Data = dt;
            }
            catch (Exception ex)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                resultMsg.Data = ex.Message;
                log.Error(ex);
            }
            return Json(resultMsg);
        }

        // POST: api/UserInfo
        /// <summary>
        /// 人员信息增加
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("api/UserInfo/Add")]
        public IHttpActionResult Add(VM_Userinfo model)
        {
            log.Info(JsonConvert.SerializeObject(model));

            //Model.UserInfo mEmp = new Model.UserInfo();
            //mEmp.EmpID = model.EmpID;
            //mEmp.EmpName = model.EmpName;
            //mEmp.EmpPwd = model.EmpPwd;
            //mEmp.EmpSex = model.EmpSex;
            //mEmp.EmpTel = model.EmpTel;
            //mEmp.EmpPhone = model.EmpPhone;
            //mEmp.EmpNation = model.EmpNation;
            //mEmp.RoleID = model.RoleID;
            //mEmp.EmpJWDID = model.EmpJWDID;
            //mEmp.DepID = model.DepID;
            //mEmp.EmpAge = model.EmpAge;
            //mEmp.EmpBirthday = model.EmpBirthday;
            //mEmp.EmpDescription = model.EmpDescription;
            //mEmp.EmpCreateDateTime = DateTime.Now;
            //mEmp.EmpIsUse = 1;
            Model.UserInfo target = new Model.UserInfo();
            Type type1 = target.GetType();
            Type type2 = model.GetType();
            foreach (var mi in type2.GetProperties())
            {
                var des = type1.GetProperty(mi.Name);
                if (des != null)
                {
                    try
                    {
                        des.SetValue(target, mi.GetValue(model, null), null);
                    }
                    catch
                    { }
                }
            }


            ResultMsg resultMsg = new ResultMsg();
            resultMsg.StatusCode = (int)StatusCodeEnum.Success;
            try
            {
                BLL.UserInfo bEmp = new BLL.UserInfo();
                if (!bEmp.Exists(target.UserID))
                {
                    if (new IPR_StudyMeetingMrgSys.BLL.UserInfo().Add(target)>0)
                    {
                        resultMsg.Info = "增加成功";
                        resultMsg.Count = 1;
                    }
                    else
                    {
                        resultMsg.Info = "增加失败";
                    }
                }
                else
                {
                    resultMsg.Info = "人员信息已经存在，请不要重复增加";
                }
            }
            catch (Exception ex)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                resultMsg.Data = ex.Message;
                log.Error(ex);
            }
            return Json(resultMsg);
        }

        // POST: api/UserInfo
        /// <summary>
        /// 人员信息分页查找
        /// </summary>
        /// <param name="swhere">查询条件</param>
        /// <param name="page">页索引</param>
        /// <param name="limit">页大小</param>
        /// <returns></returns>
        [HttpGet]
        [Route("api/UserInfo/Search")]
        public IHttpActionResult Search(string swhere, int page, int limit)
        {
            ResultMsg resultMsg = new ResultMsg();
            resultMsg.StatusCode = (int)StatusCodeEnum.Success;
            try
            {
                int startindex = (page - 1) * limit + 1;
                int endindex = page * limit;
                if (!string.IsNullOrEmpty(swhere == null ? string.Empty : swhere.Trim()))
                {
                    Dictionary<string, string> jsonObject = JsonConvert.DeserializeObject<Dictionary<string, string>>(swhere);
                    swhere = string.Empty;
                    swhere = " 1=1 ";
                    if(LoginUser.DepLevel==0)
                    {
                        //登录用户是段级别查询所有人员

                    }
                    else if(LoginUser.DepLevel==1)
                    {
                        //登录用户是车间级别，查询车间下面所有人员
                        swhere += " and DeptID in (select DepID as DeptID from Dep where DepPID="+LoginUser.DepID.ToString()+") ";
                    }
                    else if(LoginUser.DepLevel==2)
                    {
                        //登录用户是车队级别，查询车队下面所有人员
                        swhere += " and DeptID=" + LoginUser.DepID.ToString();
                    }
                    foreach (var item in jsonObject)
                    {
                        if (item.Key == "UserID")
                        {
                            swhere += $" and UserID like '%{item.Value}%'";
                        }
                        if (item.Key == "UserName")
                        {
                            swhere += $" and UserName like '%{item.Value}%'";
                        }
                        if (item.Key == "RoleID")
                        {
                            if (!string.IsNullOrEmpty(item.Value))
                                swhere += $" and T.RoleID = '{item.Value}'";
                        }
                    }
                }
                int rowCount = 0;
                DataSet dsSearch = new IPR_StudyMeetingMrgSys.BLL.UserInfo().GetListByPage(swhere, "FID", startindex, endindex, out rowCount);
                resultMsg.Info = rowCount > 0 ? StatusCodeEnum.Success.GetEnumText() : "未获取到相应数据";
                resultMsg.Count = rowCount;
                resultMsg.Data = dsSearch.Tables[0];
            }
            catch (Exception ex)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                resultMsg.Data = ex.Message;
                log.Error(ex);
            }
            return Json(resultMsg);
        }


     
        #region 读取部门下的人员
        [HttpPost]
        [Route("api/UserInfo/SelNextTree")]
        public IHttpActionResult GetNextDepTreeList(VM_Dep model)
        {
            //int CurrentDeptId = LoginUser.UserInfo.DeptID ?? 0;
            //获取下级部门列表  只读去 仅次于当前级别的 下级部门  
            ResultMsg resultMsg = new ResultMsg();
            var str = "0";
            if (model.DepIDs.IndexOf(",") > -1)
            {
                var depids = model.DepIDs.Split(',');
                foreach (var item in depids)
                {
                    str += ",'" + item + "'";
                }
            }
            else
            {
                str = "'" + model.DepIDs + "'";
            }
            DataTable dt = new IPR_StudyMeetingMrgSys.BLL.UserInfo().GetList(" RoleID='5' and DeptID in(" + str+ ")  order BY GroupsOrderNum,UserName ").Tables[0];
            if (dt.Rows.Count > 0)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                resultMsg.Info = StatusCodeEnum.Success.GetEnumText();
                var VM_TreeList = Tree.GetVM_TreeList_User(dt);
                resultMsg.Data = VM_TreeList;
            }
            else
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                resultMsg.Info = "没有获取到部门信息";
                resultMsg.Data = "";
            }
            return Json(resultMsg);
        }
        #endregion


        /// <summary>
        /// 人员信息编辑
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("api/UserInfo/Edit")]
        public IHttpActionResult Edit(Model.UserInfo model)
        {
            log.Info(JsonConvert.SerializeObject(model));
            ResultMsg resultMsg = new ResultMsg();
            resultMsg.StatusCode = (int)StatusCodeEnum.Success;
            try
            {
                if (new IPR_StudyMeetingMrgSys.BLL.UserInfo().Update(model))
                {
                    resultMsg.Info = "编辑成功";
                    resultMsg.Count = 1;
                }
                else
                {
                    resultMsg.Info = "编辑失败";
                }
            }
            catch (Exception ex)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                resultMsg.Data = ex.Message;
                log.Error(ex);
            }
            return Json(resultMsg);
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("api/UserInfo/UpdatePwd")]
        public IHttpActionResult UpdatePwd(VM_Pwd obj)
        {
            //log.Info(JsonConvert.SerializeObject(obj));
            string oriUserPwd = obj.OriUserPwd;
            string NewUserPwd = obj.NewUserPwd;
            string SureUserPwd = obj.SureUserPwd;
            ResultMsg resultMsg = new ResultMsg();
            resultMsg.StatusCode = (int)StatusCodeEnum.Success;
            try
            {
                string errMsg = "";
                if (new IPR_StudyMeetingMrgSys.BLL.UserInfo().UpdatePwd(oriUserPwd.Trim(), NewUserPwd.Trim(),SureUserPwd.Trim(), LoginUser.UserInfo.UserID,out errMsg))
                {
                    resultMsg.Info = "密码修改成功";
                    resultMsg.Count = 1;
                }
                else
                {
                    resultMsg.Info = errMsg;
                    resultMsg.StatusCode = -1;
                }
            }
            catch (Exception ex)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                resultMsg.Data = ex.Message;
                log.Error(ex);
            }
            return Json(resultMsg);
        }

        /// <summary>
        /// 人员信息删除(根据人员工号)
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("api/UserInfo/Del")]
        public IHttpActionResult Del(Model.UserInfo model)
        {
            log.Info(JsonConvert.SerializeObject(model));

            ResultMsg resultMsg = new ResultMsg();
            resultMsg.StatusCode = (int)StatusCodeEnum.Success;
            try
            {
                if (new IPR_StudyMeetingMrgSys.BLL.UserInfo().Delete(model.FID))
                {
                    resultMsg.Info = "删除成功";
                    resultMsg.Count = 1;
                }
                else
                {
                    resultMsg.Info = "删除失败";
                }
            }
            catch (Exception ex)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                resultMsg.Data = ex.Message;
                log.Error(ex);
            }
            return Json(resultMsg);
        }
        #region 用户信息上传
        [HttpPost]
        [Route("api/UserInfo/Upload")]
        public IHttpActionResult FileUpload()
        {
            ResultMsg resultMsg = new ResultMsg();
            resultMsg.StatusCode = (int)StatusCodeEnum.Success;
            try
            {
                //int EQSubject = Convert.ToInt32(string.IsNullOrWhiteSpace(HttpContext.Current.Request["EQSubject"]) ? "0" : HttpContext.Current.Request["EQSubject"]);
                var file = HttpContext.Current.Request.Files.Count > 0 ? HttpContext.Current.Request.Files[0] : null;
                if (file != null && file.ContentLength > 0)
                {
                    string fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + Path.GetFileName(file.FileName);
                    string path = HttpContext.Current.Server.MapPath("~/UploadTemp");
                    Directory.CreateDirectory(path);
                    file.SaveAs(Path.Combine(path, fileName));
                    ExcelHelper excelHelper = new ExcelHelper(Path.Combine(path, fileName));
                    DataTable dataTable = excelHelper.ExcelToDataTable(0, 1);
                    if (dataTable.Rows.Count == 0)
                    {
                        resultMsg.Info = "未获取到上传数据";
                        return Json(resultMsg);
                    }

                    foreach (DataRow dr in dataTable.Rows)
                    {
                        Model.UserInfo mEmp = new Model.UserInfo();

                        mEmp.UserID = dr[0].ToString();
                        //mEmp.UserSFZH = dr[1].ToString();
                        mEmp.UserPwd = dr[0].ToString();
                        //mEmp.UserNo = dr[2].ToString();
                        //mEmp.UserSGZH = dr[3].ToString().Split('/')[0].Trim();
                        mEmp.UserName = dr[1].ToString();

                        string deptnames = dr[2].ToString();
                        string[] celldeptname = deptnames.Split('/');
                        DataTable dt = new BLL.Dep().GetAllList().Tables[0];
                        int iCurNoExist = -1;
                        int pid = -1;
                        //沈阳机务段 / 沈阳运用车间 / 长春车队 / 指导组1
                        for (int i = celldeptname.Length - 1; i >= 0; i--)
                        {
                            DataRow[] mySelRow = dt.Select(" DepName='" + celldeptname[i].Trim() + "' ");
                            if (mySelRow.Length > 0)
                            {
                                mEmp.DeptID = int.Parse(mySelRow[0][1].ToString());
                                pid = int.Parse(mySelRow[0][1].ToString());
                                break;
                            }
                            else
                            {
                                iCurNoExist = i;

                            }
                        }
                        if(iCurNoExist>0)
                        {
                            for (int i = iCurNoExist; i <= celldeptname.Length-1; i++)
                            {
                                Model.Dep mDep = new Model.Dep();
                                mDep.DepID = new BLL.SysManage().GetMaxId("Dep", "DepID");
                                mDep.DepName = celldeptname[i];
                                mDep.DepPID = pid;
                                mDep.DepLevel = i;
                                mDep.IsDelete = 0;
                                new BLL.Dep().Add(mDep);
                                mEmp.DeptID = mDep.DepID;
                            }
                        }
                        //mEmp.DeptID = dr[0].ToString();

                        mEmp.Post = dr[3].ToString();
                        mEmp.Sex = dr[4].ToString();
                        mEmp.Nation = dr[5].ToString();

                        //mEmp.WorkBeforeEdu = dr[9].ToString();
                        //mEmp.CurrentEdu = dr[10].ToString();
                        //mEmp.Politic = dr[11].ToString();
                        //mEmp.Birthday = dr[12].ToString();
                        //mEmp.BeginWorkDate = dr[13].ToString();
                        //mEmp.AppointmentDate = dr[14].ToString();
                        //mEmp.InTime = dr[15].ToString();
                        //mEmp.EmployeeStatus = dr[16].ToString();
                        //mEmp.TechnicalGrade = dr[17].ToString();
                        //mEmp.TechnicalPost = dr[18].ToString();
                        //mEmp.IsGT = string.IsNullOrEmpty(dr[19].ToString()) ? 0 : dr[19].ToString() == "是" ? 1 : 0;
                        //mEmp.IsBZZ = string.IsNullOrEmpty(dr[20].ToString()) ? 0 : dr[20].ToString() == "是" ? 1 : 0;
                        //mEmp.PostStatus = dr[21].ToString();
                        //mEmp.isTYZYGZ = string.IsNullOrEmpty(dr[22].ToString()) ? 0 : dr[22].ToString() == "是" ? 1 : 0;
                        //mEmp.IsZYXCGZ = string.IsNullOrEmpty(dr[23].ToString()) ? 0 : dr[23].ToString() == "是" ? 1 : 0;
                        //mEmp.define1 = dr[24].ToString();
                        //mEmp.define2 = dr[25].ToString();
                        //mEmp.define3 = dr[26].ToString();
                        //mEmp.UserID7 = dr[27].ToString();
                        //mEmp.DriverType = dr[28].ToString();
                        //mEmp.DriverLicense = dr[29].ToString();

                        //暂时先取消，默认导入用户角色为（司机/副司机）
                        //int iCurRoleIDExist = -1;
                        //DataSet dsRole = new BLL.Role().GetList(" RoleName='"+ dr[8].ToString() + "' ");
                        //if(dsRole!=null)
                        //    if(dsRole.Tables.Count>0)
                        //        if(dsRole.Tables[0].Rows.Count>0)
                        //        {
                        //            iCurRoleIDExist = 1;
                        //            mEmp.RoleID = Convert.ToInt32( dsRole.Tables[0].Rows[0]["RoleID"].ToString());
                        //        }
                        //if(iCurRoleIDExist<0)
                        //{
                        //    Model.Role myRole = new Model.Role();
                        //    myRole.RoleID = new BLL.SysManage().GetMaxId("Role", "RoleID");
                        //    myRole.RoleName = dr[8].ToString();
                        //    mEmp.RoleID = myRole.RoleID;
                        //}
                        mEmp.RoleID = 5;//司机副司机的ID为2需要确定最后是否要改，设置过后，不能允许修改

                        mEmp.Groups = dr[6].ToString();

                        #region 获取指导组ID
                        if (mEmp.Groups.Contains("一") || mEmp.Groups.Contains("1"))
                            mEmp.GroupsOrderNum = 1;
                        else if (mEmp.Groups.Contains("二") || mEmp.Groups.Contains("2"))
                            mEmp.GroupsOrderNum = 2;
                        else if (mEmp.Groups.Contains("三") || mEmp.Groups.Contains("3"))
                            mEmp.GroupsOrderNum = 3;
                        else if (mEmp.Groups.Contains("四") || mEmp.Groups.Contains("4"))
                            mEmp.GroupsOrderNum = 4;
                        else if (mEmp.Groups.Contains("五") || mEmp.Groups.Contains("5"))
                            mEmp.GroupsOrderNum = 5;
                        else if (mEmp.Groups.Contains("六") || mEmp.Groups.Contains("6"))
                            mEmp.GroupsOrderNum = 6;
                        else if (mEmp.Groups.Contains("七") || mEmp.Groups.Contains("7"))
                            mEmp.GroupsOrderNum = 7;
                        else if (mEmp.Groups.Contains("八") || mEmp.Groups.Contains("8"))
                            mEmp.GroupsOrderNum = 8;
                        else if (mEmp.Groups.Contains("九") || mEmp.Groups.Contains("9"))
                            mEmp.GroupsOrderNum = 9;
                        else mEmp.GroupsOrderNum = 1;
                        #endregion


                        if (!new BLL.UserInfo().Exists(mEmp.UserID, mEmp.UserSFZH, mEmp.UserNo))
                        {
                            new BLL.UserInfo().Add(mEmp);
                        }
                    }
                    resultMsg.Info = "上传成功";
                    resultMsg.Count = dataTable.Rows.Count;
                }
                else
                {
                    resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                    resultMsg.Info = "部门不存在或上传的文件为空";
                }
            }
            catch (Exception ex)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                resultMsg.Data = ex.Message;
                log.Error(ex);
            }
            return Json(resultMsg);
        }
        /// <summary>
        /// 获取上传数据的试题类型
        /// </summary>
        /// <param name="ETName">试题类型名称</param>
        /// <returns></returns>
        private int GetUploadETID(string ETName)
        {
            switch (ETName)
            {
                case "选择":
                    return 1;
                case "判断":
                    return 2;
                case "填空":
                    return 3;
                case "简答":
                    return 4;
                case "综合":
                    return 5;
                default:
                    return 0;
            }
        }
        #endregion

        /// <summary>
        /// 人员信息删除(根据人员工号)
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("api/UserInfo/DelList")]
        public IHttpActionResult DelList(string delidlist)
        {
            log.Info(JsonConvert.SerializeObject(delidlist));

            ResultMsg resultMsg = new ResultMsg();
            resultMsg.StatusCode = (int)StatusCodeEnum.Success;
            try
            {
                if (new IPR_StudyMeetingMrgSys.BLL.UserInfo().DeleteList(delidlist))
                {
                    resultMsg.Info = "删除成功";
                    resultMsg.Count = 1;
                }
                else
                {
                    resultMsg.Info = "删除失败";
                }
            }
            catch (Exception ex)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                resultMsg.Data = ex.Message;
                log.Error(ex);
            }
            return Json(resultMsg);
        }


        // PUT: api/UserInfo/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE: api/UserInfo/5
        public void Delete(int id)
        {
        }


    }
}
